const express = require('express');
const router = express.Router();
const md5 = require('md5')
const jwt = require('jsonwebtoken')
// 导入配置文件
const {secret} = require('../../config/config')

const UserModel = require('../../models/UserModel')


// 登录
router.post('/login', (req, res) =>{
  let { username, password } = req.body
  UserModel.findOne({username, password: md5(password)}).then(data => {
    if(!data) {
      // return res.send('账号或密码错误~')
      return res.json({
        code: '2002',
        msg: '账号或密码错误',
        data: null
      })
    }
    // 创建当前用户token
    const token = jwt.sign({
      username: data.username,
      _id: data._id
    }, secret, {
      expiresIn: 60 * 60 * 24 * 7
    })
    // 响应token
    res.json({
      code: '0000',
      msg: '登录成功！',
      data: token
    })
  }).catch(err => {
    // res.status(500).send('登录失败~')
    res.json({
      code: '2001',
      msg: '数据库读取失败',
      data: null
    })
    console.log(err)
    return
  })
})

// 退出登录
router.post('/logout', (req, res) => {
  req.session.destroy(() => {
    res.render('success', {msg: '退出成功', url: '/login'})
  })
})

module.exports = router;
